// pages/cart/cart.js
import {Cart} from '../cart/cart-model.js';
var cart = new Cart();
Page({

  /**
   * 页面的初始数据
   */
  data: {
  
  },

  /**
   * 生命周期函数--监听页面加载
   * 小程序中只加载一次
   */
  onLoad: function (options) {
   
  },

 
  /**
   * 生命周期函数--监听页面显示
   * 进入页面就加载一次
   */
  onShow: function () {
    //缓存中获取购物车数据
    var cartData = cart.getCartDataFromLocal();
    //获取选中商品的价格
    this._setCal(cartData);
    // console.log('selectCounts', this.data.selectCounts);
    // console.log('selectedTypeCounts', this.data.selectedTypeCounts);
    // console.log('totalPrice', this.data.totalPrice);
    // console.log('cartData', this.data.cartData);
  },

  //计算购物车中选中商品价格
  _setCal:function(data){
    var cal = this._getTotalPrice(data);
    this.setData({
      selectCounts: cal.selectedCounts,
      totalPrice: cal.totalPrice,
      selectedTypeCounts: cal.selectedTypeCounts,
      cartData: data
    })
  },
 
 //获取选中的商品的总价格
  _getTotalPrice:function(data){
     //所需要计算的总价格，该价格是选中的商品的总价格
     var totalPrice = 0;
     //购买商品的总个数
     var selectedCounts = 0;
     //购买商品种类的总数
     var selectedTypeCounts = 0;
     for(var i=0;i<data.length;i++) {
       if (data[i].selectStatus){
          //js中小数计算事会出现一定的误差，所以转换成正整数计算
          totalPrice += data[i].price * 100 * data[i].counts * 100;
          selectedCounts += data[i].counts
          selectedTypeCounts++;
        }
     }
    return {
      selectedCounts: selectedCounts,
      selectedTypeCounts: selectedTypeCounts,
      totalPrice: totalPrice / (100 * 100)
    };
  },


  /**  
   * 商品数量的改变
   */
  changeNum:function(e){
    var id = this.getEvenData(e,'id');
    var types = this.getEvenData(e,'type');
    var data = cart.changeCartNum(id,types);
    this.setData({
        cartData:data
    })
    this._setCal(data);
  },

  /**
   * 删除该商品
   */
  delete:function(e){
    var id = this.getEvenData(e,'id');
    var data = cart.deleteCart(id)
    this.setData({
      cartData:data
    })
    this._setCal(data);
  },

  //点击选中
  toggleSelect:function(e){
    var index = this.getEvenData(e,'index');
    var status = this.getEvenData(e,'status');
    var cartData = this.data.cartData;
    cartData[index].selectStatus = !status;
    this.setData({
      cartData:cartData
    })
    cart.execSetStorageSync(cartData);
    this._setCal(cartData);
  },

  //全选
  toggleSelectAll:function(e){
    //获取布尔值的时候，前端要和js页面数据类型是一致的，要不都是字符串类型的布尔，要不就是纯粹的布尔
    var status = this.getEvenData(e,'status');
    var cartData = this.data.cartData;
    for(var i=0;i<cartData.length;i++){
      cartData[i].selectStatus = !status;
    }
    cart.execSetStorageSync(cartData);
    this._setCal(cartData);
  },

  submitOrder:function(e){
      wx.navigateTo({
        url: '../order/order?totalprice=' + this.data.totalPrice+'&from=cart'
      })
  },



  /* 获取even中的数据 */
  getEvenData:function(e,key){
       return e.currentTarget.dataset[key];
  }




})